checkCookieEnabled = ->
    cookie = document.cookie
    document.cookie = "testcookie"
    cookieEnabled = document.cookie.indexOf("testcookie") >= 0
    document.cookie = cookie
    return cookieEnabled

getQueryChannel = ->
    href = location.href.toString();
    queryInHrefIndex = href.indexOf("?")
    if queryInHrefIndex
        mq = href.match(/[?&]_c=(\w+)/)
        return mq && mq[1]
    null

getUidCookie = ->
    cookie = document.cookie
    return null unless cookie
    cookies = cookie.split(";")
    for c in cookies
        mc = c.match(/c=(.+);?/)
        ci = mc && mc[1]
        return ci if ci
    null

window._ts = ->
    uid = getUidCookie()
    if uid
        qc = getQueryChannel()
        return if qc == uid

        href = location.href.toString()
        queryInHrefIndex = href.indexOf("?")
        if queryInHrefIndex < 0
            href2 = href + "?_c=" + uid
        else
            if qc
                href2 = href.replace(/(^.+[?&]_c=)(\w+)(.*$)/, "$1" + uid + "$3")
            else
                href2 = href.slice(0, queryInHrefIndex + 1) + "_c=" + uid + "&" + href.slice(queryInHrefIndex + 1)

        location.href = href2
    else if not checkCookieEnabled()
        href = location.href.toString()
        queryInHrefIndex = href.indexOf("?")
        if queryInHrefIndex < 0
            href2 = href + "?_nocookie=true"
        else
            href2 = href + "&_nocookie=true"

        script = document.createElement('script')
        script.src = href2
        document.getElementsByTagName('head')[0].appendChild(script)


